#include "GlobalFiducialParser.h"

#include "LocationParser.h"
#include "StandardShapeParser.h"
#include "XformParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

GlobalFiducialParser::GlobalFiducialParser(
    XformParser *&_xformParser
    , LocationParser *&_locationParser
    , StandardShapeParser *&_standardShapeParser
):    m_xformParser(_xformParser)
    , m_locationParser(_locationParser)
    , m_standardShapeParser(_standardShapeParser)
{

}

bool GlobalFiducialParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new GlobalFiducial());

    /* Attributes */

    QStringRef data;

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("Xform"))
        {
            if (!m_xformParser->parse(reader))
                return false;
            auto result = m_xformParser->result();
            m_result->xformOptional = Optional<Xform*>(result);
        }
        else if (name == QStringLiteral("Location"))
        {
            if (!m_locationParser->parse(reader))
                return false;
            auto result = m_locationParser->result();
            m_result->location = result;
        }
        else if (m_standardShapeParser->isSubstitution(name))
        {
            if (!m_standardShapeParser->parse(reader))
                return false;
            auto result = m_standardShapeParser->result();
            m_result->standardShape = result;
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

GlobalFiducial *GlobalFiducialParser::result()
{
    return m_result.take();
}

}